package com.awesome.spring.mqtt.service;

/**
 * @program: awesome-spring
 * @description:
 * @author: Alex Wu
 * @createDate: 2025-03-19 10:27
 **/
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MqttService {

    @Autowired
    private  MqttClient mqttClient;

    public void publish(String topic, String payload) throws MqttException {
        if (!mqttClient.isConnected()) {
            mqttClient.reconnect();
        }
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(1);
        mqttClient.publish(topic, message);
        System.out.println("发送 MQTT 消息：" + payload);
    }
}
